<template>
  <el-upload class="op-upload"
    :class="{disabled, 'no-btn': limit <= fileList.length, picture: listType==='picture'}"
    style="display: inline-block"
    ref="upload"
    :limit="limit"
    :drag="drag"
    :data="mData"
    :dir="dir"
    :disabled="disabled || loading"
    v-bind="$attrs"
    :headers="headers"
    :listType="listType"
    action=""
    :http-request="httpRequest"
    :showFileList="!url"
    :file-list="fileList"
    :before-upload="handleBefore"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :on-error="handleError"
  >
    <template v-if="limit > fileList.length">
      <template v-if="drag">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
      <el-button :loading="loading" plain="plain" v-else :disabled="disabled" size="small" type="primary">{{btnText}}</el-button>
    </template>
   <div class="el-upload__tip" slot="tip" v-if="$slots.default">
      <slot></slot>
    </div>
  </el-upload>
</template>

<script>
// import urls from '../api/urls'
import { constant } from '../utils/index'
import { request } from './conn'
export default {
  name: 'OsUpload',
  props: {
    plain: { type: Boolean, default: true },
    drag: Boolean,
    btnText: { type: String, default: '点击上传' },
    successMessage: { type: [String, Boolean] },
    // errorMessage: {type: String, default: '上传失败'},
    type: Array,
    size: { type: Number, default: 80 },
    disabled: Boolean,
    limit: { type: Number, default: 10 },
    url: String,
    dir: String,
    publicDir: Boolean,
    value: {},
    listType: String,
    object: Boolean,
    download: Boolean,
    data: {}
  },
  data () {
    return {
      loading: false,
      headers: {
        'X-Access-Token': localStorage.getItem('token') || '',
        'web-client-type': 'web'
      },
      mData: this.data || {},
      fileList: []
    }
  },
  computed: {
    uploadAction () {
      return this.url || (this.publicDir ? constant.filePath.arrUploadPublic : constant.filePath.arrUpload)
    }
  },
  watch: {
    value: {
      handler (val) {
        if (typeof val === 'string') {
          return
        }
        let re = this.value || []
        re = Array.isArray(re) ? re : [re]
        this.fileList = re.map(item => ({ ...item, name: item.name || item.attachName }))
      },
      immediate: true
    },
    fileList (val) {
      if (this.object) {
        this.$emit('input', this.limit === 1 ? val[0] : val)
      } else {
        this.$emit('input', val.map(a => a.id).join(';'))
      }
    }
  },
  methods: {
    httpRequest (fileObj) {
      const formData = new FormData()
      formData.append('file', fileObj.file)
      for (const [key, value] of Object.entries(this.mData)) {
        formData.append(key, value + '')
      }
      return request('post', this.uploadAction, formData, { download: this.download })
    },
    handleBefore (file) {
      // 文件类型校验
      const extName = file.name.split('.').pop().toLowerCase()
      if (this.type && !this.type.includes(extName)) {
        this.$utils.message.error('不支持的文件类型')
        return false
      }
      // 文件大小校验
      if (file.size > this.size * 1024 * 1024) {
        this.$utils.message.error(`只能上传不大于${this.size}MB的文件`)
        return false
      }
      this.mData.attachType = extName
      if (!this.url && !this.dir && !this.publicDir) {
        this.$utils.message.error('请指定参数：dir')
        return false
      }
      this.mData.source = this.dir
      this.loading = true
    },
    handlePreview (file) {
      if (file.url) {
        if (this.listType === 'picture') {
          this.$utils.dialog('查看', <img src={file.url}/>, { width: '60%' })
        } else {
          window.open(file.url)
        }
      }
    },
    handleExceed (files, fileList) {
      if (this.limit) {
        this.$utils.message.error(`只能上传 ${this.limit} 个文件`)
      }
    },
    // 手动触发上传
    upload () {
      this.$refs.upload.submit()
    },
    handleRemove (file, fileList) {
      const index = this.fileList.findIndex(f => f.id === file.id)
      if (index >= 0) {
        this.fileList.splice(index, 1)
      }
    },
    handleSuccess ({ data, error }, file, fileList) {
      this.loading = false
      if (error) {
        this.$utils.message.error(error.message)
        const index = fileList.findIndex(f => f.uid === file.uid)
        fileList.splice(index, 1)
        this.$emit('error', error.message)
      } else {
        if (this.successMessage !== false) {
          this.$utils.message.success(this.successMessage || '上传成功')
        }
        if (!this.url) {
          file.id = data.id
          this.fileList.push({
            name: data.attachName,
            ...data
          })
        }
        this.$emit('success', { result: data })
      }
    },
    // handleSuccess(response, file, fileList) {
    //   this.loading = false
    //   if (response.code !== 200) {
    //     this.$utils.message.error(response.message)
    //     const index = fileList.findIndex(f => f.uid === file.uid)
    //     fileList.splice(index, 1)
    //     this.$emit('error', response.message)
    //   } else {
    //     if (this.successMessage !== false) {
    //       this.$utils.message.success(this.successMessage || '上传成功')
    //     }
    //     if (!this.url) {
    //       file.id = response.result.id
    //       this.fileList.push({
    //         name: response.result.attachName,
    //         ...response.result
    //       })
    //     }
    //     this.$emit('success', response)
    //   }
    // },
    handleError (err, file, fileList) {
      this.loading = false
      this.$utils.message.error(err.message)
      this.$emit('error', err)
    }
  }
}
</script>

<style lang="scss" scoped>
.op-upload /deep/ .el-upload-list{
  max-width: 500px;
  .el-upload-list__item-name::after {
    content: '\ff08\4e0b\8f7d\ff09';
    position: absolute;
    top: 0;
    right: 15px;
    color: #C73632;
  }
  /deep/ .el-icon-close-tip {
    display: none!important;
  }
}
.disabled /deep/ .el-upload-list i{
  display: none;
}
.no-btn /deep/.el-upload--text, .no-btn /deep/ .el-upload--picture{
  display: none;
}
.picture /deep/ .el-upload-list__item-name::after {
  display: none;
}
</style>
